<?php
/**
 * Created by PhpStorm.
 * User: admin
 * Date: 2018/12/3
 * Time: 11:32
 */

namespace app\admin\controller\crm;
use app\common\controller\Backend;
use Think\Db;
use app\admin\model\AuthGroup;
use think\Session;
class Statistics extends Backend
{
    protected  $linkBuser = '';
    protected  $linkAllot = '';
    protected  $linkProduct = '';
    protected  $admin_data = array();
    protected  $groupidArray = array();
    public function _initialize()
    {
        parent::_initialize();
      $this->linkBuser = new \app\admin\model\Buser;
      $this->linkAllot = new \app\admin\model\Allot;
      $this->linkProduct = new \app\admin\model\Product;
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        $this->model = new \app\admin\model\Allot;
        //查询当前admin权限
        $adminData = Session::get("admin");
        $linkAdmin = Db::name('Admin');
        $linkGroup = Db::name('auth_group');
        $this->admin_data = $linkAdmin->field('a.*,g.id AS gid,g.name,g.pid')->alias('a')->join('fa_auth_group_access u','a.id = u.uid','LEFT')
            ->join('fa_auth_group g','u.group_id = g.id','LEFT')
            ->where(array('a.id'=>$adminData['id']))->find();
        //判断当前用户是否是销售部人员
        $user_verification=false;
        $this->user_verification($this->admin_data['pid'],'销售部',$user_verification);
        if($user_verification){
            //销售部人员
            //查询所有下级销售专员
            $this->childrenGroupIds = $this->auth->getChildrenGroupIds(true);
            $groupList = collection(AuthGroup::where('id', 'in', $this->childrenGroupIds)->select())->toArray();//获取用户权限
            foreach ($groupList as $k=>$v){
                $this->groupidArray[] = $v['id'];
            }
            if($adminData['id']==7){
                //销售助理查询圆总的数据
                $this->groupidArray[] = 2;
            }
            $groupData = array();
            if($this->admin_data['id']==6||$this->admin_data['id']==7){
                //如果是销售部经理或者销售部助理的话查询所有分组
                $groupData = $linkGroup->where(array('pid'=>15,'status'=>'normal'))->select();
            }else if($this->admin_data['pid']==10||$this->admin_data['pid']==11||$this->admin_data['pid']==12){
                //组长查询当前组
                $groupData = $linkGroup->where(array('id'=>$this->admin_data['pid'],'status'=>'normal'))->select();
            }
        }else{
            //查询销售部人员
            $this->di_group(13,$this->groupidArray);
            //查询所有分组
            $groupData = $linkGroup->where(array('pid'=>15,'status'=>'normal'))->select();
        }
        //查询销售部全员
        $linkAdmin = Db::name('admin');
        $xiaoData = $linkAdmin->field('a.nickname,a.id')->alias('a')
            ->join('fa_auth_group_access c','a.id = c.uid','LEFT')
            ->where(array('c.group_id'=>array('IN',$this->groupidArray)))->select();
        $this->view->assign(array(
            'admin_group_id'=>$this->admin_data['gid'],
            'admin_nickname'=>$adminData['nickname'],
            'admin_data'=>$this->admin_data,
            'groupData'=>$groupData,
            'xiaoData'=>$xiaoData
        ));
    }
    /**
     * 数据统计
     * @return \think\response\Json|void
     */
    public function index($userlist=''){
        if($this->request->isAjax()){
            $param = $this->request->param();
            $field = json_decode($param['filter'],true);
            $field['createtime'] = isset($field['createtime'])?$field['createtime']:'';
            $field['allot_date'] = isset($field['allot_date'])?$field['allot_date']:'';
            $field['product'] = isset($field['product'])?$field['product']:'';
            $param['wf_admin_id'] = isset($param['wf_admin_id'])?$param['wf_admin_id']:'';
            $param['wf_group_id'] = isset($param['wf_group_id'])?$param['wf_group_id']:'';
            //获取当前用户权限
            $adminWhere = array();
            if($param['wf_admin_id']){
                //查询指定的销售专员数据
                $adminWhere['a.admin_id'] = $param['wf_admin_id'];
            }else if($param['wf_group_id']){
                //查询当前销售组数据
                $groupArray = array();
                $this->di_group($param['wf_group_id'],$groupArray);
                if($param['wf_group_id']==12){
                    $groupArray[] = 2;
                }
                $linkAdmin = Db::name('auth_group_access');
                $adminIdArray = $linkAdmin->where(array('group_id'=>array('IN',$groupArray)))->column('uid');
                $adminWhere['a.admin_id'] = array('IN',$adminIdArray);
            }else {
                $linkAuto = Db::name('auth_group_access');
                $adminId = $linkAuto->where(array('group_id'=>array('IN',$this->groupidArray)))->column('uid');//客服ID
                if($adminId){
                    $adminWhere['a.admin_id'] = array('IN',$adminId);
                }
            }
            $time = time();
            $whereOne = array(0,$time);//默认查询时间
           if($field['createtime']){
               $clearTime = explode(' - ',$field['createtime']);
               $whereOne[0] = $clearTime[0];
               $whereOne[1] = $clearTime[1];
           }
            $whereTwo  = array(0,$time);
           if($field['allot_date']){
               $allot_date = explode(' - ',$field['allot_date']);
               $whereTwo[0] = $allot_date[0];
               $whereTwo[1] = $allot_date[1];
           }
            $planWhere['a.allot_date'] = array('EGT',0);
           if($field['product']){
               $planWhere['p.product'] = array('LIKE','%'.$field['product'].'%');
           }
            //查询有效用户和无效用户
            $typeUserArray = array();
            for ($i = 1;$i<=2;$i++){
                $youCount = $this->linkBuser->alias('b')->force('createtime')->join('fa_allot a','b.`id` = a.`buser_id`','LEFT')
                ->where(array('b.typelist'=>''.$i.'','a.userlist'=>'1'))
                ->where($adminWhere)
                ->whereTime('b.createtime','between', $whereOne)->group('b.id')->count();//有效用户
                $typeUserArray[] = $youCount;
            }
            //统计客户状态数量
            $statusUserCountArray = array();
            for($i = 0;$i<=6;$i++){
                $statusUserCount=$this->linkAllot->alias('a')->where(array('a.status'=>''.$i.''))
                    ->whereTime('a.allot_date','between', $whereTwo)
                    ->where($adminWhere)
                    ->where(array('a.userlist'=>'1'))
                    ->force('allot_date')->count();//
                $statusUserCountArray[] = $statusUserCount;
            }
            //产品统计
            $planData = $this->linkProduct->field('p.product,a.buser_id,a.status')
                        ->alias('p')->join('fa_allot a','p.id = a.product_id','LEFT')
                        ->where($planWhere)
                        ->where($adminWhere)
                        ->where(array('a.userlist'=>'1'))
                        ->order('p.id')
                        ->select();
            $planData = collection($planData)->toArray();
       /*     $planCount = array_count_values(array_column($planData,'product'));//统计产品人数
            print_r($planCount);
            die;*/
            $productArray = array('name'=>array(),'userCount'=>array(),'signCount'=>array());
            $planDame = '';
            $buser_id = array();
            $signCount = array();
            foreach ($planData as $k=>$v){
                if($planDame!=$v['product']&&$k>0){
                    //装入统计数据
                    $productArray['name'][] = $planDame;
                    $productArray['userCount'][] = count($buser_id);
                    $productArray['signCount'][] = count($signCount);
                    $buser_id = array();
                    $signCount = array();
                }
                $planDame = $v['product'];
                if(!in_array($v['buser_id'],$buser_id)){
                    $buser_id[] = $v['buser_id'];
                }
                if($v['status']==6){
                    //签约客户
                    if(!in_array($v['buser_id'],$signCount)){
                        $signCount[] = $v['buser_id'];
                    }
                }
            }
            if($planDame){
                $productArray['name'][] = $planDame;
                $productArray['userCount'][] = count($buser_id);
                $productArray['signCount'][] = count($signCount);
            }
            $data = array('typeUserArray'=>$typeUserArray,'statusUserCountArray'=>$statusUserCountArray,'productArray'=>$productArray);
            return json($data);
        }
        return $this->view->fetch();
    }

    /**
     * 网贷客户分析
     */
    /*public function platform(){
        if($this->request->isAjax()){
            //判断平台有效还是无效
            $this->searchFields = 'product';
            $linkProduct = Db::name('Product');
            $countArray = array();//图形数据
            for($i = 1;$i<=2;$i++){
                $count = $linkProduct->where(array('type'=>$i))->count();
                $countArray[] = $count;
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $count = $linkProduct->where($where)->count();
            $list = $linkProduct->where($where)->order($sort,$order)->limit($offset,$limit)->select();
            $list = collection($list)->toArray();
            $result = array('total'=>$count,"rows" => $list,'countArray'=>$countArray);
            return json($result);
        }
        return $this->view->fetch();
    }*/
/*    public function planAdd(){
        $link = Db::connect([
            'type'        => 'mysql',
            // 数据库连接DSN配置
            'dsn'         => '',
            // 服务器地址
            'hostname'    => '116.62.78.18',
            // 数据库名
            'database'    => 'tw_onesh_net',
            // 数据库用户名
            'username'    => 'tw_onesh_net',
            // 数据库密码
            'password'    => 'nFyksTjZnEiCMSaw',
            // 数据库连接端口
            'hostport'    => '',
            // 数据库连接参数
            'params'      => [],
            // 数据库编码默认采用utf8
            'charset'     => 'utf8',
            // 数据库表前缀
            'prefix'      => 'cmf_',
        ]);//链接天网数据库
        $planData = $link->name('platform')->select();
        $linkProduct = Db::name('Buser');
        foreach ($planData as $v){
            $field = array(
                ''
            );
            $linkProduct->where(array('product'=>$v['pt_name']))->update($field);
        }
        echo '成功';
    }*/
    /**
     * 跟进统计
     */
    public function buserfollow_count(){
        if($this->request->isAjax()){
            $param = $this->request->param();
            $field = json_decode($param['filter'],true);
            $field['createtime'] = isset($field['createtime'])?$field['createtime']:'';
            $field['wf_group_id'] = isset($field['wf_group_id'])?$field['wf_group_id']:'';
            $field['wf_admin_id'] = isset($field['wf_admin_id'])?$field['wf_admin_id']:'';
            $param['sort'] = isset($param['sort'])?$param['sort']:'';
            $param['order'] = isset($param['order'])?$param['order']:'';
            $whereTime = array();
            $where = array('a.createtime'=>array(array('EGT',0),array('ELT',time())));
            if($field['createtime']){
                $clearTime = explode(' - ',$field['createtime']);
                $qiTime = strtotime($clearTime[0]);
                $outTime = strtotime($clearTime[1]);
                $whereTime['f.createtime'] = array(array('EGT',''.$qiTime.''),array('ELT',''.$outTime.''));
            }
            if($field['wf_admin_id']){
                $where['a.id'] = $field['wf_admin_id'];
            }else if($field['wf_group_id']){
                //查询销售组下专员跟进数据
                $groupArray = array();
                $this->di_group($field['wf_group_id'],$groupArray);
                if($field['wf_group_id']==12){
                    //带入销售部经理
                    $groupArray[] = 2;
                }
                $where['c.group_id'] = array('IN',$groupArray);
            }else {
                //查询权限内的数据
                $where['c.group_id'] = array('IN',$this->groupidArray);
            }
            $linkAdmin = Db::name('admin');
            $data = $linkAdmin->field('a.id,a.nickname,COUNT(f.id) AS count,t.buser_id')->alias('a')->force('createtime')
                    ->join('fa_allot t','t.admin_id = a.id','LEFT')
                    ->join('fa_buserfollow f','`f`.`allot_id` = `t`.`id`','LEFT')
                    ->join('fa_auth_group_access c','c.uid = a.id','LEFT')
                    ->where($where)
                    ->where($whereTime)
                    ->where(array('t.userlist'=>'1'))
                    ->order('a.id')
                    ->group('a.id,t.buser_id')->select();
            if($data){
                $totalArray = array(0);
                $adminCountArray =array(0);
                $orderCount = array();//排序
                $dataArray = array();
                $adminData = array('id'=>'','name'=>'');
                $admin_id = array();//记录以及统计的销售专员
                foreach ($data as $k=>$v){
                    if($adminData['id']!=$v['id']&&$k>0){
                        //装入头一个用户的数据
                        $orderCount[] = $adminCountArray[0];
                        $admin_id[] = $adminData['id'];
                        $totalArray[0]+=$adminCountArray[0];
                        $dataArray[] = array(
                            'id'=>$adminData['id'],
                            'nickname'=>$adminData['name'],
                            'fastcount'=>$adminCountArray[0],
                        );
                        //清空数据
                        $adminCountArray[0] = 0;
                        $adminData['id'] = '';
                        $adminData['name'] = '';
                    }
                    $adminData['id'] = $v['id'];
                    $adminData['name'] = $v['nickname'];
                    if($v['count']>0){
                        $adminCountArray[0]+=1;
                    }
                }
                if($adminData['id']){
                    //存在数据|装入最后一个统计数据
                    $orderCount[] = $adminCountArray[0];
                    $admin_id[] = $adminData['id'];
                    $totalArray[0]+=$adminCountArray[0];
                    $dataArray[] = array(
                        'id'=>$adminData['id'],
                        'nickname'=>$adminData['name'],
                        'fastcount'=>$adminCountArray[0],
                    );
                }
                if(empty($field['wf_admin_id'])&&empty($field['wf_group_id'])){
                    $where['a.id'] = array('NOT IN',$admin_id);
                    $adminUser = $linkAdmin->field('a.id,a.nickname')->alias('a')->force('createtime')
                                ->join('fa_auth_group_access c','c.uid = a.id','LEFT')
                                ->where($where)->order('a.id')->select();
                    foreach ($adminUser as $k=>$v){
                        $dataArray[] = array(
                            'id'=>$v['id'],
                            'nickname'=>$v['nickname'],
                            'fastcount'=>0,
                        );
                        $orderCount[] = 0;
                    }
                }
                //排序
                if($param['order']){
                    $orderType = ($param['order']=='desc')?SORT_DESC:SORT_ASC;
                }else{
                    $orderType = SORT_DESC;
                }
                array_multisort($orderCount,$orderType,$dataArray);
            }else{
                //没有数据默认数据
                $dataArray = array();
                $totalArray[0] = 0;
               $adminUser = $linkAdmin->field('a.id,a.nickname')->alias('a')->force('createtime')
                            ->join('fa_auth_group_access c','c.uid = a.id','LEFT')
                            ->where($where)->order('a.id')->select();
               foreach ($adminUser as $k=>$v){
                   $dataArray[] = array(
                       'id'=>$v['id'],
                       'nickname'=>$v['nickname'],
                       'fastcount'=>0,
                   );
               }
            }
            $result = array("totalArray" => $totalArray, "rows" => $dataArray,'total'=>count($dataArray));
            return json($result);
        }
        return $this->view->fetch();
    }
}